package cn.edu.gxnu.dsa.stack;

public class SqStack implements IStack {
	private Object[] stackElem;
	private int top;

	public SqStack(int maxSize) {
		stackElem = new Object[maxSize];
		top = 0;
	}

	@Override
	public void clear() {
		top = 0;

	}

	@Override
	public boolean isEmpty() {
		return (top == 0);
	}

	@Override
	public int length() {
		return top;
	}

	@Override
	public Object peek() {
		if (isEmpty()) {
			return null;
		}

		return stackElem[top - 1];
	}

	@Override
	public void push(Object x) throws Exception {
		if (top != stackElem.length) {			
			stackElem[top] = x;
			top++;
		} else {
			throw new Exception("Stack is full, pushing failed!");
		}

	}

	@Override
	public Object pop() throws Exception {
		if (isEmpty()) {
			throw new Exception("Stack is empty, poping failed!");
		}
		top--;
		return stackElem[top];
	}

	public void display() {
		for (int i = 0; i < top; i++) {
			System.out.print(stackElem[i] + " ");
		}
		System.out.print("\n");
	}

}
